import { createApp } from 'vue'

import './style.css'

import App from '@/App.vue'

import ElementPlus from 'element-plus'

import 'element-plus/dist/index.css'

//引入路由

import router from "./router"

//引入pinia

import { createPinia } from "pinia"

//导入el图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

//引入永久存储方案

import persistedstate from 'pinia-plugin-persistedstate'

// import * as api from "@/api/permission"

//引入store
import useMenu from "@/store/menu"

// import dynamicRoute from "./router/dynamicRoute"

// import recursionRoute from './utils/recursionRoute'

// api.getMenulistApi()
//     .then(res => {
//         console.log(res)
//         let r = recursionRoute(dynamicRoute, res.data.menuList)
//         console.log(r)
//     })



let pinia = createPinia();



pinia.use(persistedstate)

//使用路由守卫beforeEach来阻止用户未登入的情况下访问其它页面

router.beforeEach(async (to, from) => {
    //判断用户是否登入
    let token = sessionStorage.getItem('gqq')
    if (!token) {
        //没有token表示没有登入
        if (to.path !== "/login") {
            //如果访问的不是login,那么重新跳转到login
            return { path: "/login" }
        }
    } else {
        //判断pinia的userRoutes如果是空数组,那么要重新拉取数据
        let menuStore = useMenu();
        if (menuStore.userRoutes.length == 0 && to.path !== "/login") {
            //没有用户路由,要重新拉取
            let res = await menuStore.FETCH_MENULIST()
            console.log(res)
            //动态添加路由,需要废弃原本进入的路由,然后重新进入动态添加的路由
            return {
                ...to
            }
        }
    }
})

//全局后置守卫
router.afterEach(function (to, from) {
    console.log(to.matched)
    //不需要matched数组中,路径为"/" 的这条数据
    let breadcrumb = to.matched.filter(item => item.path !== "/")
    //   console.log(breadcrumb)
    let menuStore = useMenu();
    //存到Pinia中
    menuStore.breadcrumb = breadcrumb;
})

let app = createApp(App)
//全局注册el图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(ElementPlus)

app.use(router)

app.use(pinia)

app.mount('#app')
